package com.woniu.util.service;

import com.woniu.core.entity.CoreUser;
import com.woniu.core.mapper.CoreUserMapper;
import com.woniu.finance.entity.FinanceUser;
import com.woniu.finance.mapper.UserMapper;
import com.woniu.platform.entity.PlatformUser;
import com.woniu.platform.mapper.PlatformUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class
SecurityService implements UserDetailsService {
    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;

    @Autowired(required = false)

    private PlatformUserMapper platformUserMapper;

    @Autowired(required = false)
    private UserMapper financeUserMapper;

    @Autowired
    private CoreUserMapper coreUserMapper;

    /**
     * @param username 页面传过来的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //平台的验证
        PlatformUser platformUser = platformUserMapper.getUserByUserName(username);
        //融资企业的验证
        FinanceUser usersInfoByUserName = financeUserMapper.getUsersInfoByUserName(username);
        //下面自己添加核心企业用户
        CoreUser coreUser = coreUserMapper.selectUserByUserAccount(username);
        if (platformUser != null) {
            String join = String.join(platformUser.getPlatformrole().getAuthority());
            return new User(platformUser.getAccount(), passwordEncoder.encode(platformUser.getPasswd()),
                    AuthorityUtils.commaSeparatedStringToAuthorityList(join)
            );
        } else if (usersInfoByUserName != null) {
            String join = String.join(usersInfoByUserName.getRole().getAuthority());
            return new User(usersInfoByUserName.getUserName(), passwordEncoder.encode(usersInfoByUserName.getPasswd()),
                    AuthorityUtils.commaSeparatedStringToAuthorityList(join)
            );

        }
        else if (coreUser != null) {
            String join = String.join(coreUser.getCoreAuth().getAuthCode());
            return new User(
                    coreUser.getUserAccount(),
                    passwordEncoder.encode(coreUser.getUserPassword()),
                    AuthorityUtils.commaSeparatedStringToAuthorityList(join)
            );
        }
        else {
            throw new UsernameNotFoundException("该用户不存在");
        }
    }
}
